package com.itheima.appserver.service.impl;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.appserver.exception.MyException;
import com.itheima.appserver.exception.ResultError;
import com.itheima.appserver.interceptor.UserThreadLocal;
import com.itheima.appserver.service.SoundService;
import com.itheima.commons.constants.Constants;
import com.itheima.commons.pojo.Sound;
import com.itheima.commons.pojo.UserInfo;
import com.itheima.commons.vo.SoundVo;
import com.itheima.interfaces.SoundApi;
import com.itheima.interfaces.UserInfoApi;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Date;
@Service
public class SoundServiceImpl implements SoundService {
    @Reference
    SoundApi soundApi;
    @Autowired
    protected FastFileStorageClient storageClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;
    @Autowired
    PidService pidService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Reference
    UserInfoApi userInfoApi;

    @Override
    public void sendSound(MultipartFile multipartFile) {
        //1.先判断文件是否为空
        if (ObjectUtil.isEmpty(multipartFile)) {
            throw new MyException(ResultError.SoundIsNullError());
        }
        //2.判断语音格式是否符合要求
        String filename = multipartFile.getOriginalFilename();
        if (!StrUtil.endWithAnyIgnoreCase(filename, "m4a", ".mp3")) {
            throw new MyException(ResultError.SoundIsParseError());
        }
        //3.判断语音大小是否符合要求
        if (!(multipartFile.getSize() / 1024 / 1024 < 10)) {
            throw new MyException(ResultError.SoundSizeError());
        }
        //把语音存入到FastDFS中
        try {
            StorePath storePath = storageClient.uploadFile(multipartFile.getInputStream()
                    , multipartFile.getSize(), StrUtil.subAfter(filename, ".", true), null);
            Sound sound = new Sound();
            sound.setId(new ObjectId());
            sound.setUserId(UserThreadLocal.getUserId());
            sound.setSoundUrl(fdfsWebServer.getWebServerUrl() + storePath.getFullPath());
            sound.setCreated(System.currentTimeMillis());
            soundApi.saveSound(sound);
            String format = DateUtil.format(new Date(), "yyyy:MM:dd");
            System.out.println(format);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public SoundVo receiveSound() {
        String count = redisTemplate.opsForValue().get(Constants.SOUND + UserThreadLocal.getUserId());
        Integer countSound = Convert.toInt(count);
        if ( countSound== 0) {
            //您今日次数已用完 明天再试
            throw new MyException(ResultError.TIMESError());
        }
        //判断是否为自己语音
        Sound sound;
        while (true){
             sound = soundApi.receiveSound();
            if (sound.getUserId()!=UserThreadLocal.getUserId()){
                break;
            }
        }
        countSound--;
        redisTemplate.opsForValue().set(Constants.SOUND+UserThreadLocal.getUserId(), countSound.toString());
        UserInfo userInfo = userInfoApi.findUserInfoByUserId(sound.getUserId());
        //拼凑Vo对象返回
        SoundVo soundVo = new SoundVo();
        soundVo.setId(Convert.toInt(userInfo.getUserId()));
        soundVo.setAvatar(userInfo.getLogo());
        soundVo.setNickname(userInfo.getNickName());
        soundVo.setGender(userInfo.getSex() == 1 ? "man" : "woman");
        soundVo.setAge(userInfo.getAge());
        soundVo.setSoundUrl(sound.getSoundUrl());
        soundVo.setRemainingTimes(countSound);
        return soundVo;
    }
}
